package com.xiyu.service.dal.job;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xiyu.service.framework.job.core.handler.JobHandler;
import com.xiyu.service.model.infra.rate.InfraExchangeRate;
import com.xiyu.service.model.infra.rate.InfraExchangeRateDraft;
import com.xiyu.service.repository.infra.rate.InfraExchangeRateRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@DisallowConcurrentExecution
public class CurrencyJob implements JobHandler {

    @Resource
    private InfraExchangeRateRepository infraExchangeRateRepository;

    @Value("${xiyu.account-router_url}")
    private String accountRouterUrl;

    @Override
    public String execute(String param) throws Exception {
        log.info("开始获取汇率");
        String url = accountRouterUrl+"/devops-server/admin-api/infra/data/rate/list-query"; // 替换为你要请求的 URL

        // 发起 GET 请求
        HttpResponse response = HttpRequest.get(url)
                .header("User-Agent", "Java") // 自定义请求头
                .timeout(5000) // 设置超时时间（毫秒）
                .execute(); // 执行请求

        // 检查响应状态码
        if (response.isOk()) { // 状态码为 200
            JSONObject jsonObject = JSONUtil.parseObj(response.body());
            JSONArray rates = jsonObject.getJSONArray("data");
            for (int i = 0; i < rates.size(); i++) {
                JSONObject currencyObject = rates.getJSONObject(i);
                String currency = currencyObject.getStr("currency");
                String rate = currencyObject.getStr("rate");
                InfraExchangeRate oldRate = infraExchangeRateRepository.findByCurrency(currency).orElse(null);
                if(oldRate == null){
                    infraExchangeRateRepository.insert(InfraExchangeRateDraft.$.produce(draft -> draft.setCurrency(currency).setRate(rate)));
                }else{

                    infraExchangeRateRepository.update(InfraExchangeRateDraft.$.produce(oldRate, draft -> draft.setRate(rate)));
                }
            }

        } else {
            System.out.println("Error: Request failed with status code " + response.getStatus());
        }
        log.info("结束获取汇率");
        return "";
    }
}
